<!-- 
  * @FileDescription: 富文本编辑器
  * @Author: cc
  * @param {string} valueHtml 内容
 -->

<!-- 如果进入的是协议界面就自动插入协议相关结构 -->
<template>
  <div>
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      id="pdfDom"
      class="editorArea"
      :model-value="props.valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { Boot } from '@wangeditor/editor';
import attachmentModule from '@wangeditor/plugin-upload-attachment';
import {
  IButtonMenu,
  IDomEditor,
  IEditorConfig,
  IToolbarConfig,
  SlateTransforms,
} from '@wangeditor/editor';
import exportToPDF from './exportToPDF';
import InsertDate from './insertDate';
import InsertCellCulturePlate from './insertCellCulturePlate';
// 引入表格折叠插件
import InsertTableFolding from './tableFolding';
import module from './CustomNode/index';
import * as dayjs from 'dayjs';
import axios from 'axios';
import { useEditorStore } from '@/store/modules/editor';
import { storeToRefs } from 'pinia';

// 接收父组件传递的值
const props = defineProps({
  valueHtml: {
    type: String,
  },
});

const editorStore = useEditorStore();
const { registerFlag } = storeToRefs(editorStore);

// 注册导出为PDF文件菜单
const exportToPDFMenu = {
  key: 'exportToPDF', // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new ExportToPDF();
  },
};
// 注册插入日期菜单
const insertDateMenu = {
  key: 'insertDate', // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new InsertDate();
  },
};
// 注册插入细胞培养板菜单
const insertCellCulturePlateMenu = {
  key: 'insertCellCulturePlate', // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new InsertCellCulturePlate(cellCulturePlateOptions.value.dataName);
  },
};
// 注册插入表格折叠菜单
const insertTableFoldingMenu = {
  key: 'insertTableFolding', // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new InsertTableFolding();
  },
};
// 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
if (!registerFlag.value) {
  Boot.registerModule(module);
  Boot.registerModule(attachmentModule);
  // 插入导出为PDF菜单到工具栏
  Boot.registerMenu(exportToPDFMenu);
  // 插入日期菜单到工具栏
  Boot.registerMenu(insertDateMenu);
  // 插入细胞培养板菜单到工具栏
  Boot.registerMenu(insertCellCulturePlateMenu);
  // 插入表格折叠菜单到工具栏
  Boot.registerMenu(insertTableFoldingMenu);
  registerFlag.value = true;
}

window.addEventListener('setItem', () => {
  let newValue: any = sessionStorage.getItem('newDate');
  let newDate: any = JSON.parse(newValue);
  let insertText = dayjs(newDate).format('YYYY年MM月DD日 dddd');
  const insertDate = replaceInsertDate(insertText);
  SlateTransforms.setNodes(
    editorRef.value,
    {
      // @ts-ignore
      date: insertDate,
    },
    {
      mode: 'highest', // 针对最高层级的节点
    },
  );
});

function replaceInsertDate(insertText: string) {
  const weekMap = new Map([
    ['Monday', '星期一'],
    ['Tuesday', '星期二'],
    ['Wednesday', '星期三'],
    ['Thursday', '星期四'],
    ['Friday', '星期五'],
    ['Saturday', '星期六'],
    ['Sunday', '星期日'],
  ]);
  weekMap.forEach((value, key) => {
    if (insertText.includes(key)) {
      insertText = insertText.replace(key, value);
    }
  });
  return insertText;
}
//在工具栏中添加导出为PDF文件按钮
class ExportToPDF implements IButtonMenu {
  // TS 语法
  title: string;
  iconSvg?: string;
  tag: string;
  constructor() {
    this.title = '导出为PDF'; // 自定义菜单标题
    this.iconSvg =
      '<svg t="1704270881500" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7598" width="200" height="200"><path d="M687.57 58.3v141.9h149.48zM193.07 157.95h-70.99V877.5h576.06v-69.77H193.07z" fill="#040000" p-id="7599"></path><path d="M637.72 58.3h-398.7v709.99h598.03V247.73H637.74l-0.02-189.43z m-59.95 542.17v-83.64H364.08v-95.49h213.69V337.7l181.54 131.38-181.54 131.39z" fill="#040000" p-id="7600"></path></svg>'; // 可选
    this.tag = 'button';
  }
  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor: IDomEditor): string | boolean {
    // TS 语法
    return ' hello ';
  }
  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor: IDomEditor): boolean {
    // TS 语法
    return false;
  }
  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(editor: IDomEditor): boolean {
    // TS 语法
    return false;
  }
  // 点击菜单时触发的函数
  exec(editor: IDomEditor, value: string | boolean) {
    // TS 语法
    if (this.isDisabled(editor)) return;
    // editor.insertText(value) // value 即 this.value(editor) 的返回值
    exportToPDF('pdfDom');
  }
}

const editorConfig: Partial<IEditorConfig> = {
  // 在编辑器中，点击选中“附件”节点时，要弹出的菜单
  hoverbarKeys: {
    attachment: {
      menuKeys: ['downloadAttachment'], // “下载附件”菜单
    },
    table: {
      menuKeys: [
        'enter',
        'tableHeader',
        'tableFullWidth',
        'insertTableRow',
        'deleteTableRow',
        'insertTableCol',
        'deleteTableCol',
        'insertTableFolding',
        'deleteTable',
      ],
    },
  },
  MENU_CONF: {
    // “上传附件”菜单的配置
    uploadAttachment: {
      // server: '/api/upload', // 服务端地址
      // timeout: 5 * 1000, // 5s

      // fieldName: 'custom-fileName',
      // meta: { token: 'xxx', a: 100 }, // 请求时附加的数据
      // metaWithUrl: true, // meta 拼接到 url 上
      // headers: { Accept: 'text/x-json' },

      // maxFileSize: 10 * 1024 * 1024, // 10M

      onBeforeUpload(file: File) {
        console.log('onBeforeUpload', file);
        return file; // 上传 file 文件
        // return false // 会阻止上传
      },
      onProgress(progress: number) {
        console.log('onProgress', progress);
      },
      onSuccess(file: File, res: any) {
        console.log('onSuccess', file, res);
      },
      onFailed(file: File, res: any) {
        alert(res.message);
        console.log('onFailed', file, res);
      },
      onError(file: File, err: Error, res: any) {
        console.log(res);
        alert(err.message);
        console.error('onError', file, err, res);
      },
      //上传成功后，用户自定义插入文件
      customInsert(res: any, file: File, insertFn: Function) {
        console.log('customInsert', res);
        const { url } = res.data || {};
        if (!url) throw new Error(`url is empty`);

        // 插入附件到编辑器
        insertFn(`customInsert-${file.name}`, url);
      },
      // 用户自定义上传
      async customUpload(file: File, insertFn: Function) {
        // console.log('customUpload', file)
        // console.log(fileUpload);
        const formData = new FormData();
        formData.append('file', file);
        formData.append('id', 'PROTOCOL-1003');
        formData.append('type', 'PROTOCOL');
        console.log(file);

        axios({
          headers: {
            'Content-Type': 'multipart/form-data',
            // "Authorization": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTcwNTU0NjYzMiwidXNlcklkIjoiNjU4ZTYyYTQzYzQ0ZTIwOWM2MTlkNWNjIn0.gzwkRuUkCYmntzl7couPpFtmhFWMPtXZPBmpXckNVgw"
          },
          baseURL: '/api',
          method: 'post',
          url: '/lab-manage/eln/upload',
          data: formData,
        }).then((res) => {
          console.log(res);
          insertFn(`customUpload-${file.name}`, res.data.data);
        });
        // return new Promise(resolve => {
        //   // 插入一个文件，模拟异步
        //   setTimeout(() => {
        //     const src = `https://www.w3school.com.cn/i/movie.ogg`
        //     insertFn(`customUpload-${file.name}`, src)
        //     resolve('ok')
        //   }, 500)
        // })
      },

      // // 自定义选择
      // customBrowseAndUpload(insertFn: Function) {
      //   alert('自定义选择文件，如弹出图床')
      //   // 自己上传文件
      //   // 上传之后用 insertFn(fileName, link) 插入到编辑器
      // },

      // 插入到编辑器后的回调
      onInsertedAttachment(elem: any) {
        console.log('inserted attachment', elem);
      },
    },
    uploadImage: {
      allowedFileTypes: ['image/*'],
      // 用户自定义上传图片
      customUpload(file: File, insertFn: Function) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('id', 'PROTOCOL-1003');
        formData.append('type', 'PROTOCOL');
        console.log(file);
        axios({
          headers: {
            'Content-Type': 'multipart/form-data',
            // "Authorization": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTcwNTU0NjYzMiwidXNlcklkIjoiNjU4ZTYyYTQzYzQ0ZTIwOWM2MTlkNWNjIn0.gzwkRuUkCYmntzl7couPpFtmhFWMPtXZPBmpXckNVgw"
          },
          baseURL: '/api',
          method: 'post',
          url: '/lab-manage/eln/upload',
          data: formData,
        }).then((res) => {
          console.log(res);
          insertFn(res.data.data, `customUpload-${file.name}`, res.data.data);
        });
      },
    },
    uploadVideo: {
      // 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ['video/*'],
      // 用户自定义上传视频
      customUpload(file: File, insertFn: Function) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('id', 'PROTOCOL-1003');
        formData.append('type', 'PROTOCOL');
        console.log(file);
        axios({
          headers: {
            'Content-Type': 'multipart/form-data',
            // "Authorization": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTcwNTU0NjYzMiwidXNlcklkIjoiNjU4ZTYyYTQzYzQ0ZTIwOWM2MTlkNWNjIn0.gzwkRuUkCYmntzl7couPpFtmhFWMPtXZPBmpXckNVgw"
          },
          baseURL: '/api',
          method: 'post',
          url: '/lab-manage/eln/upload',
          data: formData,
        }).then((res) => {
          console.log(res);
          insertFn(res.data.data, `customUpload-${file.name}`);
        });
      },
    },
  },

  // 其他...
};
const toolbarConfig: Partial<IToolbarConfig> = {
  // 插入哪些菜单
  insertKeys: {
    index: 0, // 自定义插入的位置
    keys: [
      'uploadAttachment',
      'exportToPDF',
      'insertDate',
      'insertCellCulturePlate',
    ], // “上传附件”菜单
  },
  // 其他...
};
// 编辑器实例必须使用 shallowRef
const editorRef = shallowRef();
// 定义插入细胞培养板下拉框的选项
const cellCulturePlateOptions = ref({
  key: 'cellCulturePlateSelect',
  dataName: 'cellCulturePlateSelectData',
  data: [
    { value: '1536', text: '1536-well plate(32 × 48)' },
    { value: '368', text: '368-well plate(16 × 24)' },
    { value: '96', text: '96-well plate(8 × 12)' },
    { value: '48', text: '48-well plate(6 × 8)' },
    { value: '24', text: '24-well plate(4 × 6)' },
    { value: '12', text: '12-well plate(3 × 4)' },
    { value: '6', text: '6-well plate(2 × 3)' },
  ],
});
// 模拟 ajax 异步获取内容
// onMounted(() => {
//   setTimeout(() => {
//     props.valueHtml = '<p>模拟 Ajax 异步设置内容</p>'
//   }, 1500)
// })
//组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor) editor.destroy();
});
const handleCreated = (editor: string) => {
  editorRef.value = editor;
  editorRef.value[cellCulturePlateOptions.value.dataName] = {
    data: cellCulturePlateOptions.value.data,
  };
};
// Return values from setup
const mode = 'default';
</script>

<style scoped lang="scss">
:deep(.w-e-select-list ul li) {
  padding: 7px 10px;
}

:deep(tr td) {
  border-right-width: 1px !important;
}

:deep(tr th) {
  border-right-width: 1px !important;
}

// :deep(button[data-menu-key="deleteTable"],
// ) {
//   display: none !important;
// }
:deep(.editorArea) {
  height: 400px;
  min-height: 400px !important;
}

/*按钮日期选择器隐藏ipnut*/
:deep(.w-e-textarea-time-line-text) {
  position: relative !important;
}

//修改控件自带的css
:deep(.w-e-textarea-time-line-text .timepicker) {
  position: absolute; //绝对定位
  top: 0;
  left: 0;
  opacity: 0; //设置完全透明
}

:deep(.el-input__wrapper) {
  padding: 0;
}

:deep(.el-input__prefix-inner) {
  width: 180px;
}

:deep(.el-icon) {
  width: 180px;
  // height: 100px;
}

:deep(.el-input__inner) {
  display: none;
}

:deep(.el-date-editor) {
  --el-date-editor-width: 180px;
}
</style>
